//
//  OTAUpdateFirmwareNordicVc.m
//  project
//
//  Created by 黄建华 on 2018/3/27.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "OTAUpdateFirmwareNordicVc.h"
#import "AppDelegate.h"
#import "FileModelEntity.h"
#import "DownloadEntity.h"
#import "SydOTA.h"
#import "project-Swift.h"

#import "ScannedPeripheral.h"
#import "Utility.h"

@interface OTAUpdateFirmwareNordicVc ()<JCBluetoothManagerDelegate>

@property (nonatomic, assign) BOOL                 isUpdateIng;
@property (nonatomic, assign) BOOL                 updateFirmwareFinish;
@property (nonatomic, assign) BOOL                 delayUpdateButton;
@property (strong, nonatomic) NSMutableArray       *peripherals;
@property (strong, nonatomic) DFUServiceController *controller;
@property (nonatomic, strong) NSURL                *selectedFirmware;
@property (nonatomic, strong) DFUFirmware          *selectedDfuFirmware;

//奉加微升级
@property (nonatomic, strong) JCBluetoothManager *jbluetoothManager;
@property(strong,nonatomic)   NSString *OTAOrAPPType;//重新连接蓝牙时是OTA模式还是应用模式
@property(assign,nonatomic)   BOOL isFirstConnectionOTA;//判断首次连接的网络是否是OTA
@property(assign,nonatomic)   float progressValue;//完成进度
@property (nonatomic, strong) NSMutableArray *documentArr;

@end

@implementation OTAUpdateFirmwareNordicVc
    
- (void)showProgress {
    if (_showView) {
        [_showView removeFromSuperview];
        _showView = nil;
    }
    _showView = [[OTAShowView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH -80, 150)];
    [_showView showViewProgress:SN_Text(@"升级中...")];
    _showView.center = CGPointMake(kSCREEN_WIDTH/2, kSCREEN_HEIGHT/2);
    [self.view addSubview:_showView];
    //    [_showView popupWithtype:PopupViewOption_blur succeedBlock:^(UIView *View)
    //     {
    //         View.center = CGPointMake(kSCREEN_WIDTH/2, kSCREEN_HEIGHT/2);
    //     } dismissBlock:^(UIView *View)
    //     {
    //     }];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeOutBack) object:nil];
    [self performSelector:@selector(timeOutBack) withObject:nil afterDelay:20.0];
    KK_BLEConnect.isUpdateing = YES;
    _isUpdateIng = YES;
    _delayUpdateButton = YES;
}
    
- (void)timeOutBack {
    if (_isUpdateIng) {
        if (_showView.progressView.progress < 0.05) {
            [self updateFail];
            _delayUpdateButton = NO;
        }
    }
}
    
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    KK_ShareData.updateViewShow = YES;
    [self.leftButton setTintColor:[UIColor whiteColor]];
}
    
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
     [[UIView appearance] setTintColor:[UIColor whiteColor]];
    KK_ShareData.updateViewShow = NO;
    [self scanForPeripherals:NO];
    if([KK_BLEModel.chip containsString:[@"PHY" lowercaseString]])
    {
        _jbluetoothManager = nil;
        _jbluetoothManager.delegate = nil;
        [_jbluetoothManager setUpdateMode:NO];
        [KK_BLEConnect bleCenterService:YES];
        [_jbluetoothManager jbbleCenterService:NO];
    }
}
    
- (void)updateFail {
    if (_isUpdateIng) {
        SHOWMBProgressHUD(HHH_Text(@"升级失败"), nil, nil, NO, 2.0);
    }
    _updateFirmwareFinish           = NO;
    _isUpdateIng                    = NO;
    _showView.progressView.progress = 0;
    _showView.progressLabel.text    = @"0";
    [_showView removeFromSuperview];
    _showView                 = nil;
    KK_BLEConnect.isUpdateing = NO;
    HIDDENMBProgressHUD
}
    
    // 升级成功
- (void)updateFirmSuccess {
    HDAlertView *alertView = [HDAlertView alertViewWithTitle:SN_Text(@"恭喜你,升级成功!") andMessage:@""];
    [alertView addButtonWithTitle:SN_Text(@"确定") type:HDAlertViewButtonTypeDefault handler:^(HDAlertView *alertView) {
        _updateFirmwareFinish           = YES;
        _isUpdateIng                    = NO;
        [self FinishPushMainView];
    }];
    [alertView show];
}
    
- (void)FinishPushMainView {
    [kK_App enterMainVc];
}
    
- (void)updateFirmware:(NSInteger)percent {
    _showView.progressView.progress = percent * 1.0/ 100;
    //    NSLog(@"固件升级进度>>>>>>>%d %%", percent);
}
    
- (void)btnClick {
    if (_isUpdateIng == NO && _delayUpdateButton == NO) {
        if (KK_BLEModel.bleOnlineVersion > KK_BLEModel.bleVersion) {
            if (_isUpdateIng || _showView.progressView.progress > 0)
            {
                SHOWMBProgressHUD(HHH_Text(@"目前正在升级！请等待…"), nil, nil, NO, 2.0);
                return;
            }
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"新的设备固件更新")
                                                            message:SN_Text(@"检测到您的设备有新的固件更新,确定更新吗?") delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:SN_Text(@"取消"), SN_Text(@"更新"), nil];
            alert.tag = 1;
            [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
            [alert show];
            [self.leftButton setTintColor:[UIColor whiteColor]];
        } else {
            SHOWMBProgressHUD(nil, SN_Text(@"当前已为最新版本"), nil, NO, 2.0);
        }
    } else {
        SHOWMBProgressHUD(HHH_Text(@"目前正在升级！请等待…"), nil, nil, NO, 2.0);
    }
}
    
- (void)updateFirmwareClick {
    if (KK_ShareData.isDown) {
        if (![DownloadEntity sharedInstance].filePath) {
            SHOWMBProgressHUD(HHH_Text(@"没有升级文件"), nil, nil, NO, 2.0);
            [[FileModelEntity sharedInstance] checkUpdateFirmwareInfo];
            return;
        }
        NSLog(@"下载升级包成功 开始连接升级>>>>>>>>>>>>");
    } else {
        SHOWMBProgressHUD(HHH_Text(@"没有升级文件"), nil, nil, NO, 2.0);
        [[FileModelEntity sharedInstance] checkUpdateFirmwareInfo];
        return;
    }
    
    if (_showView.progressView.progress > 0.01) {
        SHOWMBProgressHUD(HHH_Text(@"目前正在升级！请等待…"), nil, nil, NO, 2.0);
        return;
    }
    
    //1:NRF升级需发送空中升级指令  2:SYD升级直接升级 只是服务是FF01
    if (_delayUpdateButton == NO) {
        if ([KK_BLEModel.chip containsString:@"nrf"]) {
            [KK_BLEConnect startUpdateFirmWare];
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(nrfUpdateFirmwareInit) object:nil];
            [self performSelector:@selector(nrfUpdateFirmwareInit) withObject:nil afterDelay:3.0];
        }
        else if([KK_BLEModel.chip containsString:@"syd"]) {
            [KK_BLESend resetSendCMD];
            NSURL  *url = [[NSURL alloc] initFileURLWithPath:[DownloadEntity sharedInstance].filePath];
            SydOTA *syd = [[SydOTA alloc]init];
            [syd OTA_START:@"FF01" data:url.absoluteString];
            DEF_WEAKSELF_(OTAUpdateFirmwareNordicVc)
            syd.sydotaProgressBlock = ^(NSInteger index) {
                [weakSelf performSelector:@selector(delayUPdateView:) withObject:StrByInt(index) afterDelay:1.0];
            };
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(onceClickUpdateButton) object:nil];
            [self performSelector:@selector(onceClickUpdateButton) withObject:nil afterDelay:5.0];
        }
        else if([KK_BLEModel.chip containsString:[@"PHY" lowercaseString]])
        {
            [self fjwUpdateFirmwareInit];
        }
        _isUpdateIng       = YES;
        _delayUpdateButton = YES;
    }
}
/*************************************奉加微升级******************************************/
- (void)fjwUpdateFirmwareInit
 {
     _isUpdateIng       = YES;
     _delayUpdateButton = YES;
     if (![DownloadEntity sharedInstance].filePath) {
         SHOWMBProgressHUD(HHH_Text(@"没有升级文件"), nil, nil, NO, 2.0);
         [[FileModelEntity sharedInstance] checkUpdateFirmwareInfo];
         return;
     }
     // 1:进入升级模式 2:显示进度条
     [self onceClickUpdateButton];
     
     [self performSelector:@selector(delayENterUpdateBle) withObject:nil afterDelay:0.5];
     NSString *commandStr = [self ToHex:0x0102];
     NSData *data = [self hexToBytes:commandStr];
     NSLog(@"发送升级指令>>>>>>>");
     [KK_BLEService senderDataToPeripheralC1:data];
}

- (void)delayENterUpdateBle
{
         [KK_BLEConnect bleCenterService:NO];
         [KK_BLEConnect initiativeDismiss];
         [_jbluetoothManager jbbleCenterService:YES];
    
         [self performSelector:@selector(UpdateFiremwareReScan) withObject:nil afterDelay:2.0];
         SHOWMBProgressHUDIndeterminate(SN_Text(@"固件开始升级..."), nil, nil);
}

- (void)UpdateFiremwareReScan
{
    [_jbluetoothManager reScan];
}

-(void)updateOTAProgressDataback:(JCBluetoothManager *)manager feedBackInfo:(float)progressValue {
    //    NSLog(@"升级进度条的值，progressValue：%.2f",progressValue);
    self.progressValue = progressValue;
    NSInteger xxx = progressValue;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayCheck) object:nil];
    if (progressValue == 100) {
        _showView.progressView.progress = 100 * 1.0/ 100;
        _showView.progressLabel.text    = [NSString stringWithFormat:@"%d%%", 100];
    }else if (progressValue == 0) {
        _showView.progressView.progress = 0 * 1.0/ 100;
        _showView.progressLabel.text    = [NSString stringWithFormat:@"%d%%", 0];
    }
    else
    {

        _showView.progressView.progress = xxx * 1.0/ 100;
        _showView.progressLabel.text    = [NSString stringWithFormat:@"%d%%", xxx];
        [self performSelector:@selector(delayCheck) withObject:nil afterDelay:3.0];
    }
}

- (void)delayCheck
{
    [_jbluetoothManager reScan];
}

//发现设备
- (void)foundPeripheral:(JCBluetoothManager *)manager peripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    JCBlutoothInfoModel *model = [[JCBlutoothInfoModel alloc]init];
    model.peripheral = peripheral;
    model.RSSI = RSSI;
    model.advertisementData = advertisementData;
    if (([peripheral.name isEqualToString:@""] || peripheral.name == nil)) {
        return;
    }
    NSString *deviceName = peripheral.name;
    BOOL found = NO;
    if([deviceName containsString:@"C1"] || [deviceName containsString:@"PPlusOTA"])
    {
        found = YES;
    }
    if (!found) {
        return;
    }
    
    NSLog(@"发现设备名: %@",peripheral.name);
    if ([peripheral.name isEqualToString:@"PPlusOTA"]) {
        [_jbluetoothManager connectToPeripheral:peripheral];
    }
}

- (void)bluetoothManager:(JCBluetoothManager *)manager didSucceedConectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"OTA peripheral.name>>>>>>%@",peripheral.name);
    if ([peripheral.name isEqualToString:@"PPlusOTA"]) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(UpdateFiremwareSendFile) object:nil];
        [self performSelector:@selector(UpdateFiremwareSendFile) withObject:nil afterDelay:1.0];
        [_jbluetoothManager stopLoopCheckCommandBuffer];
        [_jbluetoothManager stopScan];
        HIDDENMBProgressHUD
    }
}

//reboot成功之后
-(void)reBootOTASuccess:(JCBluetoothManager *)manager feedBackInfo:(BOOL)result reconnectBluetoothType:(NSString *)OTAOrAPPType {
    if (result) {
        self.OTAOrAPPType = OTAOrAPPType;
        [_jbluetoothManager disConnectToPeripheral:_jbluetoothManager.currentPeripheral];//断开蓝牙
        //扫描设备
        if (_jbluetoothManager.bluetoothState == BluetoothOpenStateIsOpen && _jbluetoothManager.currentPeripheral == nil) {
            [_jbluetoothManager reScan];
        }
    }
}

-(void)startOTASuccess:(JCBluetoothManager *)manager feedBackInfo:(BOOL)result reconnectBluetoothType:(NSString *)OTAOrAPPType {
    if (result) {
        self.OTAOrAPPType = OTAOrAPPType;
        [_jbluetoothManager disConnectToPeripheral:_jbluetoothManager.currentPeripheral];//断开蓝牙
        //扫描设备
        if (_jbluetoothManager.bluetoothState == BluetoothOpenStateIsOpen && _jbluetoothManager.currentPeripheral == nil) {
            [_jbluetoothManager reScan];
        }
    }
}

- (void)updateOTABegin
{
    HIDDENMBProgressHUD
    NSLog(@"奉加微 updateOTABegin >>>>>>>");
}

- (void)updateOTAFinish
{
    NSLog(@"奉加微 updateOTAFinish >>>>>>>");
    _updateFirmwareFinish           = YES;
    _isUpdateIng                    = NO;
    _delayUpdateButton              = NO;
    if([KK_BLEModel.chip containsString:[@"PHY" lowercaseString]])
    {
        [_jbluetoothManager setUpdateMode:NO];
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
           [self leftbuttonClick];
        });
    }
}

- (void)updateOTAError
{
    NSLog(@"奉加微 updateOTAError >>>>>>>");
}

- (void)UpdateFiremwareSendFile
{
    NSString *path = [DownloadEntity sharedInstance].filePath;
    [_jbluetoothManager updateOTAFirmwareConfirmOrder:nil andPath:path];
}

//将十进制转化为十六进制
- (NSString *)ToHex:(int)tmpid {
    NSString *nLetterValue;
    NSString *str =@"";
    int ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:
                nLetterValue = [NSString stringWithFormat:@"%u",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
    }
    if(str.length == 1 || str.length%2){
        return [NSString stringWithFormat:@"0%@",str];
    }else{
        return str;
    }
}


//字符串转data 不带0x
- (NSData*)hexToBytes:(NSString *)str
{
    NSMutableData* data = [NSMutableData data];
    int idx;
    for (idx = 0; idx+2 <= str.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [str substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}
             
/*************************************syd升级******************************************/
    // syd升级进度回调
- (void)delayUPdateView:(NSString *)indexS {
    NSInteger index = indexS.integerValue;
    
    _showView.progressView.progress = index * 1.0/ 100;
    _showView.progressLabel.text    = [NSString stringWithFormat:@"%d%%", index];
    if (index == 100) {
        [self performSelector:@selector(updateFinishLastInfo) withObject:nil afterDelay:2.0];
    }
}
    
- (void)updateFinishLastInfo {
    [self updateFirmSuccess];
}
    
- (void)onceClickUpdateButton {
    [self showProgress];
}
    
- (void)beginUpdaetFirmwareTimeOut {
    if (!_updateFirmwareFinish) {
        SHOWMBProgressHUD(HHH_Text(@"升级超时"), nil, nil, NO, 2.0);
        _isUpdateIng              = NO;
        KK_BLEConnect.isUpdateing = NO;
        _delayUpdateButton        = NO;
    }
}
    
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _isUpdateIng = NO;
    // 升级测试
    NSLog(@"手环芯片类型>>>%@",KK_BLEModel.chip);
    if([KK_BLEModel.chip containsString:[@"PHY" lowercaseString]])
    {
        _jbluetoothManager = [JCBluetoothManager shareCBCentralManager];
        _jbluetoothManager.delegate = self;
        [_jbluetoothManager setUpdateMode:true];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //开始
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            if ([KK_BLEModel.chip containsString:@"nrf"]) {
                [self updateFirmwareClick];
            } else if ([KK_BLEModel.chip containsString:@"syd"]) {
                [self updateFirmwareClick];
            }
            else if([KK_BLEModel.chip containsString:[@"PHY" lowercaseString]])
            {
                [self updateFirmwareClick];
            }
        }
    }
    //完成
    if (alertView.tag == 2) {
        [self FinishPushMainView];
    }
}
    
/*************************************NRF升级******************************************/
- (void)nrfUpdateFirmwareInit {
    if (![DownloadEntity sharedInstance].filePath) {
        SHOWMBProgressHUD(HHH_Text(@"没有升级文件"), nil, nil, NO, 2.0);
        [[FileModelEntity sharedInstance] checkUpdateFirmwareInfo];
        return;
    }
    [self nrfGetFile];
    [self nrfConnectDfu];
    [self performSelector:@selector(onceClickUpdateButton) withObject:nil afterDelay:2.0];
}
    
    // nrf连接dfu
- (void)nrfConnectDfu {
    _peripherals = [NSMutableArray arrayWithCapacity:8];
    dispatch_queue_t centralQueue = dispatch_queue_create("no.nordicsemi.ios.nrftoolbox", DISPATCH_QUEUE_SERIAL);
    _bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:centralQueue];
}
    
    // nrf升级文件
- (void)nrfGetFile {
//    NSString *filePath          = [[NSBundle mainBundle] pathForResource:@"update158.zip" ofType:nil];
//    NSURL    *url               = [[NSURL alloc] initFileURLWithPath:filePath];
    
    NSLog(@"[DownloadEntity sharedInstance].filePath>>>>%@",[DownloadEntity sharedInstance].filePath);
    NSURL    *url               = [[NSURL alloc] initFileURLWithPath:[DownloadEntity sharedInstance].filePath];
    NSString *fileNameComponent = url.lastPathComponent;
    NSString *extension         = [[fileNameComponent pathExtension] lowercaseString];
    _selectedFirmware = url;
    if ([extension isEqualToString:@"zip"]) {
        _selectedDfuFirmware = [[DFUFirmware alloc] initWithUrlToZipFile:url];
        if (_selectedDfuFirmware && _selectedDfuFirmware.fileName) {
            NSData *content = [[NSData alloc] initWithContentsOfURL:url];
            NSLog(@"fileName>>>%@ fileSize.text>>>%@ ", _selectedDfuFirmware.fileName, [NSString stringWithFormat:@"%lu bytes", (long)content.length]);
            //            [Utility showAlert:@"找到升级文件"];
        } else {
            SHOWMBProgressHUD(nil, SN_Text(@"没有升级文件"), nil, NO, 2.0);
        }
        _selectedDfuFirmware = [[DFUFirmware alloc] initWithUrlToZipFile:url type:DFUFirmwareTypeSoftdeviceBootloaderApplication];
    }
}
    
    //蓝牙
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    if (central.state == CBCentralManagerStatePoweredOn) {
        [self scanForPeripherals:YES];
    }
}
    
- (int)scanForPeripherals:(BOOL)enable {
    if (_bluetoothManager.state != CBCentralManagerStatePoweredOn) {
        return -1;
    }
    
    // Scanner uses other queue to send events. We must edit UI in the main queue
    dispatch_async(dispatch_get_main_queue(), ^{
        if (enable) {
            [_bluetoothManager scanForPeripheralsWithServices:KKBLEConfig.deviceUpdateServices
                                                      options:nil];
        } else {
            [_bluetoothManager stopScan];
        }
    });
    return 0;
}
    
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    // Scanner uses other queue to send events. We must edit UI in the main queue
    if ([[advertisementData objectForKey:CBAdvertisementDataIsConnectable] boolValue]) {
        dispatch_async(dispatch_get_main_queue(), ^{
           if ([peripheral.name isEqualToString:@"DfuTarg"]||[[peripheral.name lowercaseString]isEqualToString:[@"B2_OTA" lowercaseString]]||[[peripheral.name lowercaseString] isEqualToString:[@"XW_OTA" lowercaseString]]) {
                NSLog(@"NRF找到DfuTarg>>>>>>");
                [_bluetoothManager stopScan];
                _selectPeripheral = peripheral;
                // 准备升级
                [self performDFU];
            }
        });
    }
}
    
    // 开始NRF升级
- (void)performDFU {
    DFUServiceInitiator *initiator = [[DFUServiceInitiator alloc] initWithCentralManager:_bluetoothManager target:_selectPeripheral];
    /** 旧方法 */
    //[initiator withFirmwareFile:selectedFirmware];
    /** 新方法 */
    //    initiator                                               = [initiator withFirmware:_selectedFirmware];
    initiator.forceDfu                                             = [[[NSUserDefaults standardUserDefaults] valueForKey:@"dfu_force_dfu"] boolValue];
    initiator.packetReceiptNotificationParameter                   = [[[NSUserDefaults standardUserDefaults] valueForKey:@"dfu_number_of_packets"] intValue];
    initiator.logger                                               = self;
    initiator.delegate                                             = self;
    initiator.progressDelegate                                     = self;
    initiator.enableUnsafeExperimentalButtonlessServiceInSecureDfu = YES;
    // initiator.peripheralSelector = ... // the default selector is used
    _controller = [[initiator withFirmware:_selectedDfuFirmware]start];
}
    
    // 日志回调
- (void)logWith:(enum LogLevel) level message:(NSString *)message {
    NSLog(@"%ld: %@", (long)level, message);
}
    
    // 升级错误
- (void)dfuError:(enum DFUError) error didOccurWithMessage:(NSString *)message {
    NSLog(@"Error %ld: %@", (long)error, message);
//    [Utility showAlert:message];
//    if ([Utility isApplicationStateInactiveORBackground]) {
//        [Utility showBackgroundNotification:message];
//    }
}
    
    // 进度
- (void)dfuProgressDidChangeFor:(NSInteger)part outOf:(NSInteger)totalParts to:(NSInteger)progress currentSpeedBytesPerSecond:(double)currentSpeedBytesPerSecond avgSpeedBytesPerSecond:(double)avgSpeedBytesPerSecond {
    NSLog(@"升级>>>>part:%ld, totalParts:%ld, progress:%ld, currentSpeedBytesPerSecond:%f, avgSpeedBytesPerSecond:%f", part, totalParts, progress, currentSpeedBytesPerSecond, avgSpeedBytesPerSecond);
    NSInteger index = progress;
    _showView.progressView.progress = index * 1.0/ 100;
    _showView.progressLabel.text    = [NSString stringWithFormat:@"%d%%", index];
    if (index == 0 || index ==100 ) {
        
    }
    else
    {
        
    }
}
    
    // 升级状态
- (void)dfuStateDidChangeTo:(enum DFUState)state {
    switch (state) {
        case DFUStateConnecting:
//        SHOWMBProgressHUD(HHH_Text(@"硬件连接中..."), nil, nil, NO, 1.0);
        NSLog(@"DFUState Connecting...");
        break;
        case DFUStateStarting:
//        SHOWMBProgressHUD(HHH_Text(@"固件开始升级..."), nil, nil, NO, 1.0);
        NSLog(@"DFUState Starting DFU...");
        break;
        case DFUStateEnablingDfuMode:
//        SHOWMBProgressHUD(HHH_Text(@"启用DFU引导加载程序..."), nil, nil, NO, 1.0);
        NSLog(@"DFUState Enabling DFU Bootloader...");
        break;
        case DFUStateUploading:
//        SHOWMBProgressHUD(HHH_Text(@"固件正在上传..."), nil, nil, NO, 1.0);
        NSLog(@"DFUState Uploading...");
        break;
        case DFUStateValidating:
//        SHOWMBProgressHUD(HHH_Text(@"固件正在验证..."), nil, nil, NO, 1.0);
        NSLog(@"DFUState Validating...");
        break;
        case DFUStateDisconnecting:
//        SHOWMBProgressHUD(HHH_Text(@"固件断开..."), nil, nil, NO, 1.0);
        NSLog(@"DFUState Disconnecting...");
        break;
        case DFUStateCompleted:
        [self performSelector:@selector(updateFinishLastInfo) withObject:nil afterDelay:2.0];
        break;
        case DFUStateAborted:
//        SHOWMBProgressHUD(HHH_Text(@"固件停止升级"), nil, nil, NO, 1.0);
        break;
        default:
        break;
    }
}
    
- (void)leftbuttonClick {
    if (_isUpdateIng == NO && _delayUpdateButton == NO) {
        KK_BLEConnect.isUpdateing = NO;
        if (KK_BLEConnect.fwxOta) {
        [kK_App enterMainVc];
        }
        else
        {
        [self.navigationController popViewControllerAnimated:YES];
        }
    } else {
        SHOWMBProgressHUD(HHH_Text(@"目前正在升级！请等待…"), nil, nil, NO, 2.0);
    }
}
    
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
    /*
     #pragma mark - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
     // Get the new view controller using [segue destinationViewController].
     // Pass the selected object to the new view controller.
     }
     */
@end

